package com.ruoyi.classinfo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.classinfo.domain.Rewardqk;
import com.ruoyi.classinfo.service.IRewardqkService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/classinfo/reward")
public class RewardqkController extends BaseController {
    @Autowired
    private IRewardqkService rewardqkService;

    @GetMapping("/list")
    public TableDataInfo list(Rewardqk rewardqk,Authentication authentication) {
        // 获取当前登录用户的工号
        String teacherId = authentication.getName();
        if (teacherId != null && teacherId.startsWith("H")) {
            teacherId = teacherId.substring(1);
        }
        startPage();
        List<Rewardqk> list = rewardqkService.selectRewardListByTeacher(teacherId, rewardqk);
        return getDataTable(list);
    }

    @GetMapping("/export")
    public void export(Rewardqk rewardqk, HttpServletResponse response, Authentication authentication) {
        try {
            // 获取当前登录用户的工号
            String teacherId = authentication.getName();
            if (teacherId != null && teacherId.startsWith("H")) {
                teacherId = teacherId.substring(1);
            }

            // 设置响应头
            String fileName = "学生获奖信息_" + DateUtils.getDate() + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 查询数据
            List<Rewardqk> list = rewardqkService.selectRewardListByTeacher(teacherId, rewardqk);

            // 使用EasyExcel导出
            EasyExcel.write(response.getOutputStream(), Rewardqk.class)
                    .sheet("学生获奖信息")
                    .doWrite(list);
        } catch (Exception e) {
            // 错误处理
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                response.getWriter().println(JSON.toJSONString(AjaxResult.error("导出失败")));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
